import utils from "@/utils";
import { Utils } from "./utils";
// 标记登录是否过期
let isLoginExpired = false;
/**
 * 判断是否登录过期
 * @param res
 * @returns
 */
const isLoginExpiredFn = (res: any) => {
  let data = res?.data && res?.data[0] ? res?.data[0] : [];
  if (data.length == 0) data = res?.data ? [res?.data] : [];
  if (data.length > 0 && data[0]?.Result?.ResponseStatus?.IsSuccess == false) {
    const d = data[0]?.Result?.ResponseStatus;
    if (d?.MsgCode == 1) {
      isLoginExpired = true;
      Utils.showErr(d.Errors[0]?.Message || "", () => {
        uni.clearStorageSync();
        utils.reLaunch("home/index");
        isLoginExpired = false;
      });
      return false;
    }
  }
  return true;
};
// 设置一个定时器
let timer: any = null;
const request = (reqObj: any) => {
  const { url, showLoad = false, returnRes = false } = reqObj;
  const currentServerUrl = 'http://120.79.53.7'
  // 如果定时器存在，清除定时器
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
  if (showLoad) {
    // utils.showLoading();
    // 10秒后自动关闭
    timer = setTimeout(() => {
      utils.hideLoading();
    }, 20000);
  }

  reqObj.header = {
    "oauth-Token": utils.openId || "",
    "kdservice-sessionid": utils.getStorage("KDSVCSessionId") || "",
    "content-Type": "application/x-www-form-urlencoded",
    ...reqObj.header,
  };
  return new Promise(function (resolve, reject) {
    if (isLoginExpired) return;
    uni.request({
      ...reqObj,
      timeout: 20000,
      url: currentServerUrl + "/K3Cloud" + url,
      success: (res: any) => {
        // 判断是否请求成功
        if (res.statusCode == 200) {
          // 判断是否登录过期
          if (!isLoginExpiredFn(res)) return;
          // 判断请求是否正常
          if (res.data.success === false) {
            utils.showErr(res.data.msg || res.data.reason);
          }
          resolve(res.data);
        } else {
          utils.showErr(res.data.message || res.data.reason);
        }
      },
      fail: (err: any) => {
        utils.showErr("请求失败");
        reject(err);
        console.log(err, "err----------");
      },
      complete: () => {
        showLoad && utils.hideLoading();
      },
    });
  });
};

export default request;
